package com.purplesoft.zettl.Activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseTables.TblCart;
import com.purplesoft.zettl.DatabaseTables.TblLists;
import com.purplesoft.zettl.DatabaseTables.TblManufacturer;
import com.purplesoft.zettl.DatabaseTables.TblPurchase;
import com.purplesoft.zettl.Utilities.SharedPrefs;

public class EditLists extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

	private ListView lvLists;
	private ImageButton btAddNewList;
	private TextView tvList, tvAddNewList;
	private EditText etListName;
	private Button btCancel;
	private Cursor csTblLists;
	private SimpleCursorAdapter laLists;
	private Dialog editListDialog;
	private AlertDialog alertDialogLists;
	private DatabaseExecuter dbExec;
	private String listName;
	private final int OK_BUTTON = 1, YES_NO_BUTTON = 2;
	private boolean back_pressed = false;
	private SharedPrefs sharedPrefs;
	private final int CURRENT_LIST_ID_DEFAULT_VALUE = -99;
	private final String EQUAL_OPERATION = " = ", NOT_EQUAL_OPERATION = " != ";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_Purple);
		setContentView(R.layout.edit_lists);
        
		lvLists = (ListView) findViewById(R.id.lvLists_EditLists);
		btAddNewList = (ImageButton) findViewById(R.id.btAddList_EditLists);
		tvAddNewList = (TextView) findViewById(R.id.tvAddNewList_EditLists);
		btCancel = (Button) findViewById(R.id.btCancel_EditLists);
		
		dbExec = new DatabaseExecuter(this);
		sharedPrefs = new SharedPrefs(this);
		
		if (sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE) == CURRENT_LIST_ID_DEFAULT_VALUE) {
			btCancel.setVisibility(View.INVISIBLE);
		}
		
		selectDataForLvLists();
		btAddNewList.setOnClickListener(this);
		tvAddNewList.setOnClickListener(this);
		btCancel.setOnClickListener(this);
	}

	@Override
	public void onBackPressed() {
		if (sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE) == CURRENT_LIST_ID_DEFAULT_VALUE) {
			back_pressed = true;
			showAlertDialog(getResources().getString(R.string.no_list_selected), YES_NO_BUTTON);
		} else {
			super.onBackPressed();
		}
	}

	private void selectDataForLvLists() {
		csTblLists = dbExec.queryFromTblLists(TblManufacturer.Columns._ID, CURRENT_LIST_ID_DEFAULT_VALUE, NOT_EQUAL_OPERATION);
		startManagingCursor(csTblLists);
		laLists = new SimpleCursorAdapter(this, R.layout.edit_lists_row, csTblLists, new String[] { TblLists.Columns.ListName }, new int[] { R.id.tvList_EditListsRow });
		lvLists.setAdapter(laLists);
	}

	public void onClick(View view) {
		switch(view.getId()) {
		case R.id.btAddList_EditLists:
			showEditListsDialog(null);
			break;
		case R.id.tvAddNewList_EditLists:
			showEditListsDialog(null);
			break;
		case R.id.btCancel_EditLists:
			finish();
			break;
		case R.id.btSave_EditListsDialog:
			saveList();
			break;
		case R.id.btCancel_EditListsDialog:
			listName = null;
			editListDialog.dismiss();
			break;
		}
	}
	
	public void selectList(View view) {
		RelativeLayout editListRow = (RelativeLayout) view.getParent();
		tvList = (TextView) editListRow.findViewById(R.id.tvList_EditListsRow);
		listName = tvList.getText().toString();
		csTblLists = dbExec.queryFromTblLists(TblLists.Columns.ListName, listName, EQUAL_OPERATION);
		startManagingCursor(csTblLists);
		Bundle resultBundle = new Bundle();
		resultBundle.putInt(TblLists.Columns._ID, csTblLists.getInt(csTblLists.getColumnIndex(TblLists.Columns._ID)));
		Intent resultIntent = new Intent().putExtras(resultBundle);
		setResult(RESULT_OK, resultIntent);
		finish();
	}
	
	public void editList(View view) {
		RelativeLayout editListRow = (RelativeLayout) view.getParent();
		tvList = (TextView) editListRow.findViewById(R.id.tvList_EditListsRow);
		listName = tvList.getText().toString();
		showEditListsDialog(listName);
	}

	public void deleteList(View view) {
		RelativeLayout editListRow = (RelativeLayout) view.getParent();
		tvList = (TextView) editListRow.findViewById(R.id.tvList_EditListsRow);
		listName = tvList.getText().toString();
		showAlertDialog(getResources().getString(R.string.delete_list), YES_NO_BUTTON);
	}
	
	private boolean checkIfAllFieldsAreFilled() {
		if (etListName.getText().toString().equals("")) {
			showAlertDialog(getResources().getString(R.string.fill_in_list_name), OK_BUTTON);
			return false;
		} else {
			return true;
		}
	}

	private void saveList() {
		if (checkIfAllFieldsAreFilled() == false) return;
		if (listName !=null) {
			if (dbExec.updateTblList(listName, etListName.getText().toString()) == false) {
				showAlertDialog(getResources().getString(R.string.list_already_exists), OK_BUTTON);
				etListName.selectAll();
				return;
			}
		} else {
			if (dbExec.insertIntoTblLists(etListName.getText().toString()) == false) {
				showAlertDialog(getResources().getString(R.string.list_already_exists), OK_BUTTON);
				etListName.selectAll();
				return;
			}
		}
			listName = null;
			csTblLists.requery();
			lvLists.setAdapter(laLists);
			editListDialog.dismiss();
	}

	private void showAlertDialog(String alertText, int buttons) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch(buttons) {
		case OK_BUTTON:
			builder.setMessage(alertText);
			builder.setNeutralButton(R.string.ok, this);
			break;
		case YES_NO_BUTTON:
			builder.setMessage(String.format(alertText, listName));
			builder.setCancelable(false);
		    builder.setPositiveButton(R.string.yes, this);
		    builder.setNegativeButton(R.string.no, this);
		    break;
		}
		if (alertDialogLists == null || !alertDialogLists.isShowing()) {
			alertDialogLists = builder.create();
			alertDialogLists.show();
		}
	}

	private void showEditListsDialog(String listName) {
		RelativeLayout viewGroup = (RelativeLayout) findViewById(R.id.EditListsDialog);
		LayoutInflater layoutInfater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = layoutInfater.inflate(R.layout.edit_lists_dialog, viewGroup);
		
		if (editListDialog == null || !editListDialog.isShowing()) {
			editListDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			editListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			editListDialog.setContentView(layout);
			
			WindowManager.LayoutParams lp = editListDialog.getWindow().getAttributes();
			lp.dimAmount=0.6f;
			editListDialog.getWindow().setAttributes(lp);  
			editListDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			editListDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			
			Button btSaveEditListsDialog = (Button) editListDialog.findViewById(R.id.btSave_EditListsDialog);
			Button btCancelEditListsDialog = (Button) editListDialog.findViewById(R.id.btCancel_EditListsDialog);
			TextView tvTitleEditListsDialog = (TextView) editListDialog.findViewById(R.id.tvTitle_EditListsDialog);
			etListName = (EditText) editListDialog.findViewById(R.id.etListName_EditListsDialog);
			
			if (listName != null) {
				tvTitleEditListsDialog.setText(getResources().getString(R.string.edit_list));
				etListName.setText(listName);
				etListName.selectAll();
				btSaveEditListsDialog.setText(R.string.alter);
			}
			
			btSaveEditListsDialog.setOnClickListener(this);
			btCancelEditListsDialog.setOnClickListener(this);
			
			editListDialog.show();
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		switch(which) {
		case -1: // Yes
			if (back_pressed == true) {
				finish();
			} else {
				dbExec.deleteFromTblPurchase(TblPurchase.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
				dbExec.deleteFromTblCart(TblCart.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
				dbExec.deleteFromTblLists(listName);
				selectDataForLvLists();
				Toast.makeText(this, String.format(getResources().getString(R.string.list_deleted), listName), Toast.LENGTH_LONG).show();
				listName = null;
				if (sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE) == CURRENT_LIST_ID_DEFAULT_VALUE) {
					btCancel.setVisibility(View.INVISIBLE);
				}
				back_pressed = false;
			}
			break;
		case -2: // No
			back_pressed = false;
		}
	}
}
